package com.lz.ovuola.repository.mysql;

import java.util.Map;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryDynamic", transactionManagerRef = "transactionManagerDynamic", basePackages = "com.lz.ovuola.repository.mysql", repositoryFactoryBeanClass = MyDynamicRepositoryFactoryBean.class)
public class EnableRepositoryDynamicConfig {
	@Autowired
	private JpaProperties jpaProperties;

	@Autowired
	private DynamicDataSource dynamicDataSource;

	@Bean(name = "entityManagerDynamic")
	public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
		return entityManagerFactoryDynamic(builder).getObject()
				.createEntityManager();
	}

	@Bean(name = "entityManagerFactoryDynamic")
	public LocalContainerEntityManagerFactoryBean entityManagerFactoryDynamic(
			EntityManagerFactoryBuilder builder) {
		return builder.dataSource(dynamicDataSource)
				.properties(getVendorProperties(dynamicDataSource))
				.packages("com.lz.ovuola.entity") // 设置实体类所在位置
				.persistenceUnit("primaryPersistenceUnit").build();
	}

	private Map<String, String> getVendorProperties(DataSource dataSource) {
		// return jpaProperties.getHibernateProperties(dataSource);
		Map<String, String> map = jpaProperties
				.getHibernateProperties(dataSource);
		map.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
		return map;
	}

	@Bean(name = "transactionManagerDynamic")
	PlatformTransactionManager transactionManagerPrimary(
			EntityManagerFactoryBuilder builder) {
		return new JpaTransactionManager(entityManagerFactoryDynamic(builder)
				.getObject());
	}

}
